package com.zhouhailin.shirospringbootdemo.service.impl;

import com.zhouhailin.shirospringbootdemo.entity.Role;
import com.zhouhailin.shirospringbootdemo.service.UserService;
import com.zhouhailin.shirospringbootdemo.dao.UserDao;
import com.zhouhailin.shirospringbootdemo.entity.Permission;
import com.zhouhailin.shirospringbootdemo.entity.User;
import com.zhouhailin.shirospringbootdemo.utils.SaltUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author zhouhailin
 * @date 2023/1/5 15:49
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public void register(User user) {
        // 1、获取随机盐
        String salt = SaltUtil.getSalt(8);
        // 2、将随机盐保存至数据库
        user.setSalt(salt);
        // 3、明文密码进行 md5 + salt + hash
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());

        // 4、保存用户至数据库
        userDao.save(user);
    }

    @Override
    public User findByUserName(String userName) {
        return userDao.findByUserName(userName);
    }

    @Override
    public List<Role> findRolesByUserName(String userName) {
        return userDao.findRolesByUserName(userName);
    }

    @Override
    public List<Permission> findPermsByRoleId(Integer id) {
        return userDao.findPermsByRoleId(id);
    }

    @Override
    public User login(User user) {

        User userLogin = userDao.login(user);
        if (null != userLogin) {
            return userLogin;
        }
        throw new RuntimeException("登录失败！");
    }
}
